import Taro, { Component } from "@tarojs/taro";
import { View, Text, Map } from "@tarojs/components";
import { connect } from "@tarojs/redux";
import { $Req } from "@utils";
import { AtForm, AtInput, AtButton, AtIcon, AtSwitch } from "taro-ui";
import "./index.scss";

@connect(
  ({ userModel }) => ({
    userModel,
  }),
  (dispatch) => ({
    userAction: dispatch.userModel,
  })
)
export default class Index extends Component {
  config = {
    navigationBarTitleText: "编辑收货地址",
  };

  constructor(props) {
    super(...arguments);
    const {
      userModel: { addressDetail },
      userAction,
    } = this.props;
    let data = {
      addressId: null,
      name: "",
      tel: "",
      address: "",
      detailed: "",
      checked: false,
    };
    if (addressDetail) {
      data = {
        addressId: addressDetail.id,
        name: addressDetail.receiverName,
        tel: addressDetail.receiverMobile,
        address: addressDetail.receiverDistrict,
        detailed: addressDetail.receiverAddress,
        checked: addressDetail.defaultFlag === 1 ? true : false,
      };
    }
    this.state = data;
  }

  componentDidMount() {}

  onSubmit() {
    this.addUserAddress();
  }

  chooseLocation() {
    wx.chooseLocation({
      success: (res) => {
        this.setState({
          address: res.address,
        });
      },
    });
  }

  // 添加地址
  async addUserAddress() {
    const {
      userModel: { userInfo },
      userAction,
    } = this.props;

    const { addressId, name, tel, checked, address, detailed } = this.state;

    if (!tel) {
      Taro.showToast({
        title: "手机号码不能为空!",
        icon:"none"
      })
      return false;
    }

    if (!(/^1[3456789]\d{9}$/.test(tel))) {
      Taro.showToast({
        title: "手机号码错误!",
        icon:"none"
      })
      return false;
    }

    if (!address) {
      Taro.showToast({
        title: "地址不能为空!",
        icon:"none"
      })
      return false;
    }

    if (!detailed) {
      Taro.showToast({
        title: "详细地址不能为空!",
        icon:"none"
      })
      return false;
    }

    if (addressId) {
      let { code, msg, data } = await $Req({
        type: "post",
        url: "/indexUser/editShippingAddress",
        data: {
          id: addressId,
          userId: userInfo.userId,
          receiverName: name,
          receiverMobile: tel,
          receiverZip: '100000',
          receiverAddress: detailed,
          receiverDistrict: address,
          defaultFlag: checked ? 1 : 0,
          createTime:'',
          updateTime:''
        },
      });
      if (code != 200) return;

    } else {
      let { code, message, data } = await $Req({
        type: "post",
        url: "/indexUser/addShippingAddress",
        data: {
          userId: userInfo.userId,
          receiverName: name,
          receiverZip: '100000',
          receiverMobile: tel,
          receiverAddress: detailed,
          receiverDistrict: address,
          defaultFlag: checked ? 1 : 0,
        },
      });
      if (code !== 200) return;
    }

    Taro.navigateBack({
      delta: 1,
    });
  }

  async delAdds() {
    let { code } = await $Req({
      type: "get",
      url: "/indexUser/delShippingAddress",
      data: {
        id: this.state.addressId
      }
    });

    if (code == 200) {
      Taro.showToast({
        title: "删除成功"
      })

      Taro.navigateBack({
        delta: 1,
      });
    } else {
      return;
    }
  }

  deleteAddress = () => {
    this.delAdds();
  }

  render() {
    return (
      <View className="at-row page-address-add">
        <View className="at-col c0">
          <AtForm>
            <AtInput
              name="name"
              title="收件人"
              required
              type="text"
              placeholder="请填写收件人姓名"
              value={this.state.name}
              onChange={(v) => {
                this.state.name = v;
              }}
            >
              <AtIcon value="user" size="20" color="#4D4D4D"></AtIcon>
            </AtInput>
            <AtInput
              name="tel"
              title="手机号"
              required
              type="number"
              maxLength="11"
              placeholder="请输入绑定银行卡的手机号"
              value={this.state.tel}
              onChange={(v) => {
                this.state.tel = v;
              }}
            />

            <View
              className="at-row"
            >
              <View className="at-col">
                <AtInput
                  name="address"
                  title="所在地区"
                  required
                  type="text"
                  placeholder="省、市区县、乡镇"
                  value={this.state.address}
                  onChange={(v) => {
                    this.setState({
                      address: v
                    })
                    console.log(v);
                  }}
                >
                  <AtIcon value="map-pin" size="20" color="#4D4D4D" onClick={() => {
                this.chooseLocation();
              }}></AtIcon>
                </AtInput>
              </View>
            </View>

            <AtInput
              name="detailed"
              title="详细地址"
              type="text"
              required
              placeholder="街道、楼牌号等"
              value={this.state.detailed}
              onChange={(v) => {
                this.state.detailed = v;
              }}
            />
          </AtForm>
          <View className="at-row at-row__align--center at-row-swich">
            <View
              className="at-col at-col-8"
              style="padding:10PX;padding-left:20PX;"
            >
              <View className="at-row at-row__align--center">
                <View className="at-col">
                  <Text>设置默认地址</Text>
                </View>
              </View>
              <View className="at-row at-row__align--center swich-remind">
                <View className="at-col">
                  <Text>提醒：每次下单都会默认使用该地址</Text>
                </View>
              </View>
            </View>
            <View
              className="at-col at-col-4"
              style="padding:10PX;text-align:right;"
            >
              <AtSwitch
                border={false}
                checked={this.state.checked}
                onChange={(v) => {
                  this.state.checked = v;
                }}
              />
            </View>
          </View>
          <View className="at-row at-row__justify--center at-row__align--center at-row-del">
            <View className="at-col btn-col">
              <AtButton circle className="btn-del" onClick={this.deleteAddress}>
                删除
              </AtButton>
            </View>
          </View>
          <View className="at-row at-row__justify--center at-row__align--center at-row-save">
            <View className="at-col btn-col">
              <AtButton
                circle
                type="primary"
                className="btn-save"
                onClick={() => {
                  this.onSubmit();
                }}
              >
                保存
              </AtButton>
            </View>
          </View>
        </View>
      </View>
    );
  }
}
